<template>
  <div>
    <div>
      <el-row class="nav">
        <span class="font-weight">工单流程</span>
      </el-row>
      <el-divider></el-divider>
      <el-form :inline="true"
               class="coverage-style-searchForm">
        <el-form-item>
          <div class="demo-input-suffix">
            <el-input placeholder="请输入流程名称"
                      clearable
                      v-model="core"
                      class="key-word-search"
                      prefix-icon="el-icon-search"></el-input>
          </div>
        </el-form-item>
        <el-form-item>
          <button @click="handleSearch"
                  type="button"
                  class="el-button el-button--primary el-button--medium h30Btn ">查询</button>
        </el-form-item>
        <el-form-item class="fr">
          <button @click="createWorkOrderType"
                  type="button"
                  class="el-button el-button--primary el-button--medium h30Btn ">新建工单流程
          </button>
        </el-form-item>
      </el-form>
      <el-row>
        <el-table ref="multipleTable"
                  stripe
                  border
                  v-loading="loading"
                  :header-cell-style="{background:'#F2F3F8'}"
                  :data="tableData"
                  tooltip-effect="dark"
                  style="width: 100%"
                  @select="pinSelect"
                  @selection-change="handleSelectionChange">
          <el-table-column type="selection"
                           min-width="10%"
                           align="center"></el-table-column>
          <el-table-column prop="name"
                           label="工单流程"
                           min-width="15%"
                           class="label-name"
                           align="center"
                           style="color:green">
            <template slot-scope="scope">
              <span @click="lookDetail(scope.row.id)"
                    style="color: #2393f1;cursor:pointer;text-decoration: underline;">{{scope.row.name}}</span>
            </template>
          </el-table-column>
          <el-table-column label="状态"
                           min-width="15%"
                           align="center">
            <template slot-scope="scope">{{ scope.row.useStatus == 1 ? '启用' : '停用'}}</template>
          </el-table-column>
          <el-table-column label="最近修改时间"
                           min-width="15%"
                           align="center">
            <template slot-scope="scope">{{scope.row.lastUpdateTime ? timestampToTime(scope.row.lastUpdateTime) : ""}}</template>
          </el-table-column>
          <el-table-column prop="lastUserName"
                           label="最近修改人"
                           min-width="15%"
                           align="center"></el-table-column>
          <el-table-column label="操作"
                           show-overflow-tooltip
                           align="center"
                           min-width="30%">
            <template slot-scope="scope">
              <!-- <el-button
              icon="el-icon-delete"
              type="text"
              size="mini"
              v-if="scope.row.useStatus"
              @click="handleChange(scope.$index, scope.row)"
            >停用</el-button>
            <el-button
              icon="el-icon-circle-check"
              type="text"
              size="mini"
              v-else
              @click="handleChange(scope.$index, scope.row)"
            >启用</el-button>-->
              <el-button type="text"
                         size="mini"
                         class="run-and-stop"
                         @click="handleChange(scope.$index, scope.row)">
                <!-- <i class="el-icon-circle-check"></i> -->
                <span v-if="scope.row.useStatus !== 1">
                  <img src="../../../assets/images/start.png"
                       alt />启用
                </span>
                <span v-else>
                  <img src="../../../assets/images/stop.png"
                       alt />停用
                </span>
              </el-button>
              <el-button icon="el-icon-edit"
                         type="text"
                         size="mini"
                         @click="handleEdit(scope.$index, scope.row)">编辑
              </el-button>
              <el-button icon="el-icon-delete"
                         type="text"
                         size="mini"
                         @click="handleDelete(scope.$index, scope.row)">删除
              </el-button>
              <el-button icon="el-icon-view"
                         type="text"
                         size="mini"
                         @click="lookOrderTypeInfo(scope.row)">查看接口</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-row>
      <el-row class="paging-foot page-foot-spacing"
              :gutter="20">
        <el-col :span="12">
          <span class="color-select">批量操作</span>
          <span class="select-number">（已选中{{selectAllIdLength}}条）</span>
          <button @click="deleteBatch"
                  type="button"
                  class="el-button el-button--primary el-button--medium h30Btn ">删除</button>
        </el-col>
        <el-col :span="12">
          <div>
            <el-pagination background
                           class="el-pagination-style"
                           v-show="totalDataLength > 0"
                           @size-change="handleSizeChange"
                           @current-change="handleCurrentChange"
                           :current-page="page"
                           :page-sizes="[10, 20, 50, 100]"
                           :page-size="pageSize"
                           layout="total, sizes, prev, pager, next, jumper"
                           :total="totalDataLength"></el-pagination>
          </div>
        </el-col>
      </el-row>
    </div>
    <!--查看工单接口的弹框-->
    <el-dialog title="接口详情"
               v-dialogDrag
               :visible.sync="lookPortInfoShow"
               width="50%">
      <div class="demo-input-suffix"
           v-if='lookPortInfoData'>
        <div class='per-demo-input-suffix'
             v-for='(item,index) in lookPortInfoData.requestParam'
             :key='index'>
          <span class='label_info'>{{item.param}}:</span>
          <el-input readonly
                    v-if='item.value'
                    v-model='item.value'>{{item.value}}</el-input>
          <el-input readonly
                    v-if='!item.value'
                    v-model='item.paramMeaning'>{{item.paramMeaning}}</el-input>
        </div>
        <div class='per-demo-input-suffix'>
          <span class='label_info'>接口地址:</span>
          <el-input readonly
                    v-model='lookPortInfoData.requestUrl'>{{lookPortInfoData.requestUrl}}</el-input>
        </div>
        <div class='per-demo-input-suffix'>
          <span class='label_info'>备注:</span>
          <div>外部转入创建工单须在接口中传入处理信息的列表:externalFlowInfo(外部列表信息字段)</div>
        </div>
        <div class='per-demo-input-suffix'>
          <span class='label_info'>每条流转信息包含:</span>
          <ul style='display:flex;flex-wrap:wrap'>
            <li>dealUserName(处理人姓名)</li>
            <li>dealUserId(处理人工号)
            </li>
            <li>dealTime(处理时间)
            </li>
            <li>dealFlowNode(处理环节)
            </li>
            <li>dealOpinion(处理意见)
            </li>
          </ul>
        </div>
      </div>
      <span slot="footer"
            class="dialog-footer">
        <el-button type="primary"
                   @click="lookPortInfoShow = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>

</template>
<script>
import { deleteList, deleteBatch, updateUseStatus, selectByName, judgeEditableById } from '@/api/workType'
import { externalRequestParamShow } from '@/api/workOrderFieldReflect'
import common from '@/common/common.js'
export default {
  data () {
    return {
      searchcontent: '',
      lists: [],
      changeLists: [],
      origin: -1,
      pin: false,
      tableData: [],
      multipleSelection: [],
      core: '',
      page: 1,
      pageSize: 10,
      totalDataLength: 0,
      loading: true,
      selectAllId: [],
      selectAllIdLength: 0,
      useStatus: '',
      lookPortInfoShow: false,
      lookPortInfoData: ''
    }
  },
  created () {
    this.handleSearch()
  },
  mounted () {
    window.addEventListener('keydown', code => { // 这个是获取键盘按住事件
      // console.log(code) // 这个是你按住键盘打印出键盘信息，在浏览器中自行查看
      if (code.keyCode === 16 && code.shiftKey) { // 判断是否按住shift键，是就把pin赋值为true
        this.pin = true
      }
    })
    window.addEventListener('keyup', code => { // 这个是获取键盘松开事件
      if (code.keyCode === 16) { // 判断是否松开shift键，是就把pin赋值为false
        this.pin = false
        this.selectAllIdLength = this.selectAllId.length
        if (this.lists.length > 2) {
          this.selectAllId = this.lists
        } else {
          this.selectAllId = this.changeLists
        }
        this.selectAllIdLength = this.selectAllId.length
      }
    })
  },
  destroyed () {
    window.removeEventListener('keydown', code => {
      if (code.keyCode === 16 && code.shiftKey) {
        this.pin = true
      }
    }, false)
    window.removeEventListener('keyup', code => {
      if (code.keyCode === 16) {
        this.pin = false
      }
    }, false)
  },
  methods: {
    // 这里是select事件开始
    pinSelect (item, row) {
      const data = this.tableData // 获取所有数据
      const origin = this.origin // 起点数 从-1开始
      const endIdx = row.index // 终点数
      if (this.pin && item.includes(data[origin])) { // 判断按住
        // this.$refs.multipleTable.selectClear()
        const sum = Math.abs(origin - endIdx) + 1// 这里记录终点
        const min = Math.min(origin, endIdx)// 这里记录起点
        let i = 0

        while (i < sum) {
          const index = min + i
          this.$refs.multipleTable.toggleRowSelection(data[index], true) // 通过ref打点调用toggleRowSelection方法，第二个必须为true
          i++
        }
        this.lists = this.selectAllId
      } else {
        this.origin = row.index // 没按住记录起点或没选起点
        this.lists = []
      }
    },
    // 查看工单详情
    lookDetail (val) {
      let id = val
      judgeEditableById(id).then(res => {
        let data = res.data
        this.$store.commit('changeWorkTypeId', val)
        this.$store.commit('orderTitleFun', '查看工单流程')
        this.$router.push('/createWorkOrderType')
      })
    },
    // 查看工单流程
    lookOrderTypeInfo (val) {
      this.lookPortInfoShow = true
      let id = val.id
      externalRequestParamShow(id).then(res => {
        if (res.data.retCode === 200) {
          this.lookPortInfoData = res.data.data
        }
      })
    },
    // 编辑
    handleEdit (index, row) {
      let id = row.id
      judgeEditableById(id).then(res => {
        let data = res.data
        if (data.retCode === 200) {
          this
            .$store
            .commit('changeWorkTypeId', row.id)
          this.$store.commit('orderTitleFun', '编辑工单流程')
          this
            .$router
            .push('/createWorkOrderType')
        } else {
          this.$message({ message: res.data.msg, type: 'error' })
        }
      })
    },
    // 点击搜索
    handleSearch () {
      // this.loading = true
      this.page = 1
      this.handleSearchData()
    },
    // 点击搜索封装
    handleSearchData () {
      let params = {
        currentPage: this.page,
        name: this.core,
        pageSize: this.pageSize
      }
      selectByName(params).then(res => {
        let data = res.data
        if (data.retCode === 200) {
          this.tableData = data.data.list
          this.totalDataLength = data.data.total
          this.loading = false
          this.origin = -1
          this.tableData.forEach((item, index) => {// 遍历索引,赋值给data数据
            item.index = index
          })
        } else { }
      })
    },
    // 改变停用启用状态
    handleChange (index, row) {
      if (row.useStatus === 0) {
        this.useStatus = 1
      } else {
        this.useStatus = 0
      }
      let params = {
        id: row.id,
        userId: this.$store.state.userId,
        useStatus: this.useStatus
      }
      updateUseStatus(params).then(res => {
        let data = res.data
        if (data.retCode === 200) {
          this.$message({ message: res.data.msg, type: 'success' })
          row.useStatus = row.useStatus === 1
            ? 0
            : 1
        } else {
          this.$message({ message: res.data.msg, type: 'error' })
        }
      })
    },
    // 删除
    handleDelete (index, row) {
      let params = {
        idList: [row.id],
        userId: this.$store.state.userId
      }
      this.deleteSelect(params)
    },
    // 新建
    createWorkOrderType () {
      this
        .$store
        .commit('changeWorkTypeId', '')
      this.$store.commit('orderTitleFun', '新建工单流程')
      this
        .$router
        .push('/createWorkOrderType')
    },
    toggleSelection (rows) {
      if (rows) {
        rows.forEach(row => {
          this
            .$refs
            .multipleTable
            .toggleRowSelection(row)
        })
      } else {
        this
          .$refs
          .multipleTable
          .clearSelection()
      }
    },
    // 切换分页个数
    handleSizeChange (pageSize) {
      this.pageSize = pageSize
      this.page = 1
      this.handleSearchData()
    },
    // 切换上下分页
    handleCurrentChange (page) {
      this.page = page
      this.handleSearchData()
    },
    // 列表选择
    handleSelectionChange (val) {
      this.selectAllIdLength = val.length
      this.selectAllId = []
      val.map((value, key, index) => {
        this.selectAllId.push(value.id)
      })
      this.changeLists = this.selectAllId
    },
    // 批量删除
    deleteBatch () {
      if (this.selectAllIdLength === 0) {
        this.$message({ message: '请选择删除项', type: 'error' })
        return
      }
      let params = {
        idList: this.selectAllId,
        userId: this.$store.state.userId
      }
      this.deleteSelect(params)
    },
    deleteSelect (val) {
      this
        .$confirm('确认要删除吗？', '确认删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          center: true,
          customClass: 'messageBox-prompt-delete'
        })
        .then(() => {
          deleteBatch(val).then(res => {
            if (res.data.retCode === 200) {
              this.$message({ message: res.data.msg, type: 'success' })
              this.handleSearchData()
            } else {
              this.$message({ message: res.data.msg, type: 'error' })
            }
          })
        })
    },
    // 时间戳转换
    timestampToTime (timestamp) {
      return common.timestampToTime(timestamp)
    }
  }
}
</script>
<style scoped>
.el-button--text {
  line-height: 16px;
}

.key-word-search {
  width: 300px;
}

.select-number {
  color: #b50029;
}

> .el-button > i {
  font-size: 13px;
  margin-right: 10px;
}

.el-pagination {
  text-align: right;
}

> .el-input__icon {
  font-size: 13px;
  font-weight: 800;
}

> .el-input--prefix .el-input__inner {
  padding-left: 35px;
}
.label_info {
  display: inline-block;
  min-width: 150px;
  white-space: nowrap;
}
.per-demo-input-suffix {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}
.per-demo-input-suffix ul {
  display: flex;
  flex-wrap: wrap;
}
.per-demo-input-suffix ul li {
  margin: 0 10px 5px 0;
}
</style>